
package com.epam.android.training.day6;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class InfoContentProvider extends ContentProvider {

  private static final String DATABASE_NAME = "info.db";

  private static final int DATABASE_VERSION = 1;

  private static final String TABLE_NAME = "notes";

  private DatabaseHelper dbHelper;

  private SQLiteDatabase sqlDB;

  /**
   * Custom content provider
   * 
   * @author Natallia_Kukharchyk
   */
  private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      db.execSQL("Create table " + TABLE_NAME + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, INFO_TEXT TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
      onCreate(db);
    }
  }

  @Override
  public int delete(Uri arg0, String arg1, String[] arg2) {
    return 0;
  }

  @Override
  public String getType(Uri arg0) {
    return null;
  }

  @Override
  public Uri insert(Uri uri, ContentValues contentvalues) {
    // get database
    sqlDB = dbHelper.getWritableDatabase();
    // insert record get the row number of recently inserted record
    long rowId = sqlDB.insert(TABLE_NAME, "", contentvalues);
    if (rowId > 0) {
      Uri rowUri = ContentUris.appendId(MyInfo.Info.CONTENT_URI.buildUpon(), rowId).build();
      getContext().getContentResolver().notifyChange(rowUri, null);
      return rowUri;
    }
    throw new SQLException("Failed to insert row into " + uri);

  }

  @Override
  public boolean onCreate() {
    dbHelper = new DatabaseHelper(getContext());
    return (dbHelper == null) ? false : true;

  }

  @Override
  public Cursor query(Uri uri, String[] projection, String arg2, String[] arg3, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    qb.setTables(TABLE_NAME);
    Cursor c = qb.query(db, projection, arg2, null, null, null, sortOrder);
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;

  }

  @Override
  public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
    return 0;
  }

}
